﻿using System;
using CommandLine;
using CommandLine.Text;
using System.IO;
using Excel;
using System.Data;

namespace JsonTool
{
    class Options
    {
        [Option('i', "in", Required = true, HelpText = "输入excel文件路径")]
        public string ExcelPath { get; set; }

        [Option('o', "out", Required = true, HelpText = "输出Json文件路径")]
        public string JsonPath { get; set; }

        [Option('h', "header", Required = false, DefaultValue = 2, HelpText = "表格中有多少行是表头")]
        public int HeaderNum { get; set; }

        [Option('a', "array", Required = false, DefaultValue = false, HelpText = "转换为List，默认为字典")]
        public bool ExportArray { get; set; }

    }

    class Program
    {
        private static readonly HeadingInfo headingInfo = new HeadingInfo("excel转json");

        static void Main(string[] args)
        {
            headingInfo.WriteMessage("\n---------开始-----------");
            var options = new Options();

            if (Parser.Default.ParseArgumentsStrict(args, options, () =>
            {
                Console.WriteLine("\t转换失败，请输入正确的命令!");
                Environment.Exit(-1);
            }))
            {
                try
                {
                    Console.WriteLine("解析命令成功!");
                    Console.WriteLine("Excel路径：{0}\tJson路径：{1}\n表头行数：{2}\t转换为List：{3}",options.ExcelPath,options.JsonPath,options.HeaderNum,options.ExportArray);
                    Run(options);
                    Console.WriteLine(string.Format("{0}:转换完成", Path.GetFileName(options.ExcelPath)));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }

        static void Run(Options options)
        {
            string excelPath = options.ExcelPath;
            //加载excel文件
            FileStream excelFile = File.Open(excelPath, FileMode.Open, FileAccess.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(excelFile);

            excelReader.IsFirstRowAsColumnNames = true;
            DataSet dataSet = excelReader.AsDataSet();
            //数据检测
            if (dataSet.Tables.Count < 1)
            {
                throw new Exception("文件为空：" + excelPath);
            }
            //取得数据
            DataTable sheet = dataSet.Tables[0];
            if (sheet.Rows.Count <= 0)
            {
                throw new Exception("表格Sheet为空：" + excelPath);
            }

            if (options.JsonPath != null && options.JsonPath.Length > 0)
            {
                JsonExporter exporter = new JsonExporter();
                exporter.ExeclToDict(sheet, options.HeaderNum);
                Console.WriteLine("进行保存");
                exporter.SaveToJson(options.JsonPath,options.ExportArray);
            }
            excelFile.Close();
        }
    }
}
